package com.example.controller.cockpit;

import com.alibaba.fastjson.JSON;
import com.example.config.KieSessionUtils;
import com.example.config.redis.RedisUtils;
import com.example.controller.Rundrools;
import com.example.mapper.AlarmMapper;
import com.example.mapper.FileMapper;
import com.example.mapper.PointEqipmentMapper;

import com.example.pojo.DroolsTest;
import com.example.pojo.SeRuleFile;

import com.example.pojo.dev.fmDevInfo;

import com.example.pojo.dev.fmRoominfo;
import com.example.pojo.dev.icDevPoint;
import com.example.pojo.msgDevice;
import com.example.websocket.WebSocketServerJSC;
import org.apache.commons.lang3.StringUtils;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: 西安交大项目
 * @description: 驾驶舱数据
 * @author: cxq
 * @create: 2022年9月14日10:24:32
 **/
@Component
public class CockpitData {


    static KieHelper kieHelper1;
    @Autowired
    private PointEqipmentMapper pointEqipmentMapper;

    @Autowired
    private com.example.mapper.omMapper omMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private AlarmMapper alarmMapper;
    static SimpleDateFormat df = new SimpleDateFormat("MM-dd");
    @Value("${web.upload}")
    private String upload;
    public static String userId;
    String time1 = new String("06-01");
    String time2 = new String("12-01");
    String season = null;
    List<Map<String, Object>> lists = new ArrayList<>();
  //@Scheduled(cron = "0 0 0 * * ?")
    public void aVoid() throws ParseException {
        KieHelper kieHelper = new KieHelper();
        Date nowData = new Date();
        if (df.parse(df.format(nowData)).before(df.parse(time2)) && df.parse(df.format(nowData)).after(df.parse(time1))) {
            season = "summer";
        } else {
            season = "winter";
        }
        List<SeRuleFile> selectrbyO2 = fileMapper.selectrbyO2("探测器", season);
        if (selectrbyO2.size() == 0) {
            kieHelper1 = null;
            //kieSession = null;
        } else {
            for (SeRuleFile droolsFile : selectrbyO2) {
                try {
                    //获取规则文件
                    String dRl = KieSessionUtils.getDRl(upload + "/" + droolsFile.getSeason() + droolsFile.getUrl());
                    kieHelper1 = kieHelper.addContent(dRl, ResourceType.DRL);
                    //kieSession = kieHelper1.build().newKieSession();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        this.JSCO2();
    }

    @Scheduled(cron = "*/60 * * * * ?")
    public void JSCO2() {


        lists=new ArrayList<>();

        //查询所有气体感知设备，找到你o2探测器
        List<fmDevInfo> fdList = pointEqipmentMapper.listQiTiDevice();

        //找出氧气探测器 ，找到设备所属房间信息，和氧气浓度
        for (fmDevInfo fmDeviceinfo : fdList) {

            if (fmDeviceinfo.getDevName().contains("探测器")) {

                fmRoominfo fr = omMapper.selectfloorbydeviceName(Integer.parseInt(fmDeviceinfo.getObjectId()), fmDeviceinfo.getModelId());

                List<String> pointNames = pointEqipmentMapper.selectPointNameDistinctByDbid(fmDeviceinfo.getObjectId(), fmDeviceinfo.getModelId());
                for (String point : pointNames) {
                    //获取绑定数据的变量
                    List<icDevPoint> variname = pointEqipmentMapper.disvarname(fmDeviceinfo.getObjectId(), fmDeviceinfo.getModelId());
                    //获取绑定的数据
                    String points = (String) redisUtils.get(point);
                    if (null == points) {
                        continue;
                    }
                    //DroolsTest droolsTest = new DroolsTest();
                    List<Map<String, Object>> list = JSON.parseObject(points, List.class);
                    for (Map<String, Object> map : list) {
                        String variableName = (String) map.get("variable_name");
                        for (icDevPoint pointEquipment : variname) {
                            //获取当前值
                            if ((variableName.contains("浓度") && variableName.equals(pointEquipment.getVarName())) || (variableName.contains("压差") && variableName.equals(pointEquipment.getVarName()))) {
                                Map<String, Object> potencyMap = new HashMap<>();
                                potencyMap.put("houseNumber", fr.getHouseNumber());
                                potencyMap.put("roomName", fr.getRmName());
                                potencyMap.put("name", fmDeviceinfo.getDevName().split("探测器")[0]);


                                double value = Double.parseDouble((String) map.get("value"));
                                potencyMap.put("potency", value);
//                                droolsTest.setKey(pointEquipment.getAliasVar());
//                                droolsTest.setValue((float) value);
                                msgDevice selectbydbidandmodelid = null;
                                if (fr.getRmName().equals("原料药品存放室")){
                                    int a=0;
                                }

                                if (fr != null) {
                                    selectbydbidandmodelid = alarmMapper.selectbydbidandmodelid(Integer.valueOf(fr.getObjectId()), fr.getModelId());

                                }
                                if (selectbydbidandmodelid==null){
                                    selectbydbidandmodelid = alarmMapper.selectbydbidandmodelid(Integer.parseInt(fmDeviceinfo.getObjectId()), fmDeviceinfo.getModelId());
                                }

                                if (selectbydbidandmodelid != null) {
                                    potencyMap.put("state", selectbydbidandmodelid.getAlarmStatus());
                                } else {
                                    potencyMap.put("state", "正常");
                                }

//                                if(fr!=null) {
//                                    msgDevice selectbydbidandmodelid = alarmMapper.selectbydbidandmodelid(Integer.valueOf(fr.getObjectId()), fr.getModelId());
//                                    if (selectbydbidandmodelid!=null){
//                                        potencyMap.put("state", selectbydbidandmodelid.getAlarmStatus());
//                                    }
//                                else if (kieHelper1==null){
//                                        potencyMap.put("state", "正常");
//                                    }
//                                }else  {
//                                    //规则引擎判断
//                                    droolsTest.setDbId(Integer.valueOf(fmDeviceinfo.getObjectId()));
//                                    droolsTest.setSingal(fmDeviceinfo.getObjectId());
//                                    droolsTest.setSave(false);
//                                    KieSession kieSession1 = kieHelper1.build().newKieSession();
//
//                                    if (StringUtils.isBlank(fmDeviceinfo.getDevNumber())){
//                                        droolsTest.setPointName(fmDeviceinfo.getDevName());
//                                    }else {
//                                        droolsTest.setPointName(fmDeviceinfo.getDevName()+" "+fmDeviceinfo.getDevNumber());
//                                    }
//                                    kieSession1.insert(droolsTest);
//                                    //执行
//                                    kieSession1.fireAllRules();
//                                    kieSession1.dispose();
//                                    if (!droolsTest.getSave()){
//                                        potencyMap.put("state", "正常");
//                                    }else {
//                                        potencyMap.put("state", droolsTest.getMessageType());
//                                    }
//                                }
                                lists.add(potencyMap);
                            }


                        }

                    }


                }

            }
        }

        if (!StringUtils.isBlank(userId)) {
            WebSocketServerJSC.sendMessage(JSON.toJSONString(lists), userId);
        }


    }
    public void JSC(String userid) {
        if (!StringUtils.isBlank(userid)) {
            WebSocketServerJSC.sendMessage(JSON.toJSONString(lists), userid);
        }
    }
}
